import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [{
    path: "/",
    redirect: "/login"
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../components/login.vue')
  }, {
    path: '/home',
    name: 'Home',
    component: () => import('../components/home.vue')
  },
]




const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  // next() 放行  next('/login') 强制跳转
  // 如果用户访问的为登陆页，则直接放行
  if (to.path === '/login')
    return next();
  // 从sessionstorage中获取到保存了的token值
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token就直接跳转到login页面
  if (!tokenStr) return next('/login')
  next();


})

export default router
